//
//  PhoneOriginalViewController.m
//  NOAHWM
//
//  Created by Ryan on 13-5-30.
//  Copyright (c) 2013年 Ryan. All rights reserved.
//

#define kDynPwdDownloaderKey        @"DynPwdDownloaderKey"
#define kOldPhoneAuthDownloaderKey  @"OldPhoneAuthDownloaderKey"

#import "PhoneOriginalViewController.h"
#import "NYMemberCenterDataManager.h"
#import "JSON.h"
#import "PhoneNewViewController.h"

@interface PhoneOriginalViewController ()

@property (nonatomic, copy) NSString *tempPwd;

@end

@implementation PhoneOriginalViewController

@synthesize pwdTextField,phoneLabel;
@synthesize sendButton,nextButton;
@synthesize tempPwd;

#pragma mark - IBAction methods
- (IBAction)sendButtonClicked:(id)sender
{
    [self.pwdTextField resignFirstResponder];
    NSString *suburl = [NSString stringWithFormat:kDynamicPasswordUrl,@"jsonp",[NYMemberCenterDataManager sharedManager].loginMember.phoneNum,@"2"];
    suburl = [suburl stringByAppendingString:@"app000015"];
    NSString *url = [NSString stringWithFormat:@"%@%@",kServerAddress,suburl];
    url = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    [[RYDownloaderManager sharedManager] requestDataByGetWithURLString:url delegate:self purpose:kDynPwdDownloaderKey];
}
- (IBAction)nextButtonClicked:(id)sender
{
    [self.pwdTextField resignFirstResponder];
    NSString *validString = [self checkPasswordValid];
    if(validString)
    {
        [[RYHUDManager sharedManager] showWithMessage:validString customView:nil hideDelay:2.f];
    }
    else
    {
        NSString *suburl = [NSString stringWithFormat:kOldPhoneAuthUrl,@"jsonp",[NYMemberCenterDataManager sharedManager].loginMember.accountId,pwdTextField.text];
        suburl = [suburl stringByAppendingString:@"app000016"];
        NSString *url = [NSString stringWithFormat:@"%@%@",kServerAddress,suburl];
        url = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        [[RYDownloaderManager sharedManager] requestDataByGetWithURLString:url delegate:self purpose:kOldPhoneAuthDownloaderKey];
        [[RYHUDManager sharedManager] startedNetWorkActivityWithText:@"旧手机号码验证..."];
    }
}

#pragma mark - Private methods

- (NSString *)checkPasswordValid
{
    if(pwdTextField.text.length == 0)
        return [NSString stringWithFormat:[kRegisterPromptDict objectForKey:@"F000001E"],@"密码"];
    else if(pwdTextField.text.length > 6)
        return [NSString stringWithFormat:[kRegisterPromptDict objectForKey:@"F000002E"],@"密码"];
    else if(![pwdTextField.text isEqualToString:self.tempPwd])
        return [NSString stringWithFormat:[kRegisterPromptDict objectForKey:@"F000004E"],@"密码",@"获取的密码"];
    else
        return nil;
}

- (void)enableSendButton
{
    self.sendButton.enabled = YES;
}

#pragma mark - BaseViewController methods
- (void)leftItemTapped
{
    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(enableSendButton) object:nil];
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - UIViewController methods

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [self setNaviTitle: @"手机"];
    [self setLeftNaviItemWithTitle:@"返回" imageName:@"Icon_Back"];
    [self setRightNaviItemWithTitle:nil imageName:nil];
    self.phoneLabel.text = [NYMemberCenterDataManager sharedManager].loginMember.phoneNum;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
    if(self.isViewLoaded && !self.view.window)
    {
        [[RYDownloaderManager sharedManager] cancelDownloaderWithDelegate:self purpose:nil];
        self.view = nil;
        self.pwdTextField = nil;
        self.phoneLabel =nil;
        self.sendButton = nil;
        self.nextButton = nil;
    }
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    [[RYDownloaderManager sharedManager] cancelDownloaderWithDelegate:self purpose:nil];
    self.pwdTextField = nil;
    self.phoneLabel = nil;
    self.sendButton = nil;
    self.nextButton = nil;
}

- (void)dealloc
{
    [[RYDownloaderManager sharedManager] cancelDownloaderWithDelegate:self purpose:nil];
    [tempPwd release];
    [sendButton release];
    [nextButton release];
    [pwdTextField release];
    [phoneLabel release];
    [super dealloc];
}

#pragma mark - RYDownloaderDelegate methods
- (void)downloader:(RYDownloader*)downloader completeWithNSData:(NSData*)data
{
    //jsonp({"message":"密码已发送到您的手机上，如有疑问请拨打客服热线400-820-0025咨询","result":"1","verifycode":"227336"})
    NSString *str = [[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] autorelease];
    str = [str stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    //去掉被包的jsonp字串
    if(str.length > 7)
        str = [str substringWithRange:NSMakeRange(6, str.length-7)];
    if([downloader.purpose isEqualToString:kDynPwdDownloaderKey])
    {
        NSDictionary *dict = [str JSONValue];
        if([[dict objectForKey:@"result"] isEqualToString:@"1"])
        {
            self.tempPwd = [dict objectForKey:@"verifycode"];
            self.sendButton.enabled = NO;
            [self performSelector:@selector(enableSendButton) withObject:nil afterDelay:30.f];
        }
        else
        {
            self.tempPwd = nil;
        }
        [[RYHUDManager sharedManager] showWithMessage:[dict objectForKey:@"message"] customView:nil hideDelay:2.f];
    }
    else if([downloader.purpose isEqualToString:kOldPhoneAuthDownloaderKey])
    {
        NSDictionary *dict = [str JSONValue];
        if([[dict objectForKey:@"result"] isEqualToString:@"1"])
        {
            PhoneNewViewController *pnvc = [[PhoneNewViewController alloc] init];
            [self.navigationController pushViewController:pnvc animated:YES];
            [pnvc release];
        }
        [[RYHUDManager sharedManager] showWithMessage:[dict objectForKey:@"message"] customView:nil hideDelay:2.f];
    }
}
- (void)downloader:(RYDownloader*)downloader didFinishWithError:(NSString*)message
{
    if([downloader.purpose isEqualToString:kDynamicPasswordDownloaderKey])
    {
        self.tempPwd = nil;
    }
    else if([downloader.purpose isEqualToString:kOldPhoneAuthDownloaderKey])
    {
        
    }
    [[RYHUDManager sharedManager] showWithMessage:kNetWorkErrorString customView:nil hideDelay:2.f];
}

@end
